import Vue from 'vue'
import VueRouter from 'vue-router'

import { getToken } from '@/utils/storage'
import { Toast } from 'vant'

// 路由懒加载，异步组件改造第一种写法
// const Register = () => import('@/views/Register.vue')
const Detail = () => import('@/views/Detail.vue')
const Login = () => import('@/views/Login.vue')
const Layout = () => import('@/views/Layout.vue')
const Article = () => import('@/views/Article.vue')
const Collect = () => import('@/views/Collect.vue')
const Like = () => import('@/views/Like.vue')
const User = () => import('@/views/User.vue')

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/article' },
  // 路由懒加载，异步组件改造第二种写法
  { path: '/register', component: () => import('@/views/Register.vue') },
  { path: '/login', component: Login },
  { path: '/detail/:id', component: Detail },
  {
    path: '/',
    component: Layout,
    children: [
      { path: '/article', component: Article },
      { path: '/collect', component: Collect },
      { path: '/like', component: Like },
      { path: '/user', component: User }
    ]
  }

]

const router = new VueRouter({
  routes
})

const whitelist = ['/login', '/register']
// 导航守卫 => 全局前置守卫
router.beforeEach((to, from, next) => {
  // 执行时机：每次页面跳转都会触发
  // 只要注册了全局前置守卫，路由会立即瘫痪，必须调用next()放行
  // 参数1：to 到哪里去
  // 参数2：from 从哪里来
  // 参数3：next 函数 决定是否放行，next()表示放行，next('/路径')表示强制跳转到指定路由，next(false)表示不放行
  const token = getToken()
  if (token) {
    next()
  } else {
    // 以后白名单越来越多，会导致写起来很麻烦
    // if (to.path === '/login' || to.path === '/register') {
    if (whitelist.includes(to.path)) {
      next()
    } else {
      Toast.fail('请先登录')
      next('/login')
    }
  }
})

export default router
